﻿using Microsoft.Xna.Framework;
using SolarWinds.Helpers;

namespace SolarWinds.Particles
{
    public class CubeParticleEmitter :ParticleEmitter
    {
        public CubeParticleEmitter(ParticleEmitterDescription description) : base(description)
        {
        }

        protected override void InitParticle(ref Particle p)
        {
            // random point inside cube defined by P0 and P1 by "lerp"
            float tx = RandomHelper.RandomFloat();
            float ty = RandomHelper.RandomFloat();
            float tz = RandomHelper.RandomFloat();

            var randPoint = new Vector3
            {
                X = tx * mDescription.P0.X + (1.0f - tx) * mDescription.P1.X,
                Y = ty * mDescription.P0.Y + (1.0f - ty) * mDescription.P1.Y,
                Z = tz * mDescription.P0.Z + (1.0f - tz) * mDescription.P1.Z
            };

            // set position and velocity
            p.PreviousPosition = mDescription.Position + randPoint;
            p.Position = p.PreviousPosition;
            p.Velocity = mDescription.Direction * mDescription.Speed;

            // spread particle direction by rotation of velocity vector
            float spreadRad = MathHelper.ToRadians(mDescription.Spread);
            p.Velocity = Vector3.Transform(p.Velocity, Matrix.CreateRotationX(spreadRad * RandomHelper.RandomFloat2()));
            p.Velocity = Vector3.Transform(p.Velocity, Matrix.CreateRotationY(spreadRad * RandomHelper.RandomFloat2()));
            p.Velocity = Vector3.Transform(p.Velocity, Matrix.CreateRotationZ(spreadRad * RandomHelper.RandomFloat2()));
        }
    }
}
